package com.hellogood.yaohuo.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.hellogood.yaohuo.server.db.ConnectionPool;
import com.hellogood.yaohuo.server.db.DBHelper;
import com.hellogood.yaohuo.server.mgr.factory.MgrFactory;
import com.hellogood.yaohuo.shared.data.CallDTO;
import com.hellogood.yaohuo.shared.entity.ThDetail;
import com.hellogood.yaohuo.shared.entity.ThForm;
import com.hellogood.yaohuo.shared.exception.DatabaseException;
import com.hellogood.yaohuo.shared.vo.MainFrame;

public class ThFormDAO extends DBHelper {
	Logger log = Logger.getLogger(this.getClass());

	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<ThForm> thFormList = new ArrayList<ThForm>();
		if (rs != null) {
			while (rs.next()) {
				ThForm thForm = new ThForm();
				thForm.setThBillNo(rs.getString("ThBillNo"));
				thForm.setThDate(rs.getString("ThDate"));
				thForm.setOrgCode(rs.getString("OrgCode"));
				thForm.setVendorCode(rs.getString("VendorCode"));
				thForm.setVendorName(rs.getString("Vendorname"));
				thForm.setCounts(rs.getInt("Counts"));
				thForm.setCost(rs.getBigDecimal("Cost"));
				thForm.setNetCost(rs.getBigDecimal("NetCost"));
				thForm.setTotal(rs.getBigDecimal("Total"));
				thForm.setStaffCode(rs.getString("StaffCode"));
				thForm.setStaffName(rs.getString("StaffName"));
				thForm.setTimeMark(rs.getString("TimeMark"));
				thForm.setRzDate(rs.getString("RzDate"));
				thForm.setRemark(rs.getString("Remark"));
				thFormList.add(thForm);
			}
		}
		return thFormList;
	}

	public String getLastThBillNo(String billNo) {
		String sql = "SELECT top 1 * FROM ThForm LIKE '" + billNo + "%' ORDER BY Thbillno desc";
		List<?> list = super.query(sql);
		if (list == null || list.isEmpty()) {
			return null;
		}
		ThForm form = (ThForm) list.get(0);
		return form.getThBillNo();

	}

	public String createTuihuo(ThForm form, boolean isModify) {
		String result = "";
		List<String> sqls = new ArrayList<String>();
		if (isModify) {
			String sql = "DELETE FROM ThForm WHERE ThBillNo = '" + form.getThBillNo() + "'";
			sqls.add(sql);
			sql = "DELETE FROM ThDetail WHERE ThBillNo = '" + form.getThBillNo() + "'";
			sqls.add(sql);
		}

		String sql = "INSERT INTO ThForm(ThBillNo,ThDate,orgCode,vendorCode,vendorName,counts,cost,netCost,total,staffCode,"
				+ "staffName,rzDate,remark) VALUES('"
				+ form.getThBillNo()
				+ "',CONVERT(varchar(100), GETDATE(), 23),'"
				+ form.getOrgCode()
				+ "','"
				+ form.getVendorCode()
				+ "','"
				+ form.getVendorName()
				+ "',"
				+ form.getCounts()
				+ ","
				+ form.getCost()
				+ ","
				+ form.getNetCost()
				+ ","
				+ form.getTotal()
				+ ",'"
				+ form.getStaffCode() + "','" + form.getStaffName() + "','" + form.getRzDate() + "','" + form.getRemark() + "')";
		sqls.add(sql);

		List<ThDetail> list = form.getList();
		if (list != null && (!list.isEmpty())) {
			for (ThDetail d : list) {
				sql = "INSERT INTO ThDetail(thBillNo,pluCode,pluName,barCode,depCode,depName,bra,color,CSize,jPrice,price,"
						+ "counts,cost,netCost,total,rzDate,remark,orgCode,netJPrice) VALUES('"
						+ d.getThBillNo()
						+ "','"
						+ d.getPluCode()
						+ "','"
						+ d.getPluName()
						+ "','"
						+ d.getBarCode()
						+ "','"
						+ d.getDepCode()
						+ "','"
						+ d.getDepName()
						+ "','"
						+ d.getBra()
						+ "','"
						+ d.getColor()
						+ "','"
						+ d.getSize()
						+ "',"
						+ d.getjPrice()
						+ ","
						+ d.getPrice()
						+ ","
						+ d.getCounts()
						+ ","
						+ d.getCost()
						+ ","
						+ d.getCost()
						+ ","
						+ d.getTotal()
						+ ",'"
						+ d.getRzDate()
						+ "','" + d.getRemark() + "','" + d.getOrgCode() + "'," + d.getNetJPrice() + ")";
				sqls.add(sql);
			}
		}
		try {
			executeBatch(sqls);
		} catch (DatabaseException e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return e.getMessage();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<ThForm> searchThFormByQuyu(String quyuCode, String startDate, String endDate, String rz) {
		String userCode = MainFrame.currentUser.getStaffCode();
		String orgs = "";
		if (quyuCode == null) {
			orgs = MgrFactory.getInstance().createOrgMgr().getOrgCodeByUser(userCode);
		} else {
			orgs = MgrFactory.getInstance().createOrgMgr().getOrgCodeByUserQuyu(userCode, quyuCode);
		}

		String sql = "SELECT * FROM ThForm WHERE OrgCode IN (?) AND cast(ThDate as char(10)) >= CONVERT(VARCHAR(10),CONVERT(DATETIME,?),120) and cast(ThDate as char(10)) <= CONVERT(VARCHAR(10),CONVERT(DATETIME,?),120)";
		if (rz.equals("已入账")) {
			sql = sql + " AND rzDate <> ''";
		} else if (rz.equals("未入账")) {
			sql = sql + " AND rzDate = ''";
		}
		Object[] args = new Object[] { orgs, startDate, endDate };
		List<?> list = super.query(sql, args);
		return (List<ThForm>) list;
	}

	@SuppressWarnings("unchecked")
	public List<ThForm> searchThForm(String orgCode, String startDate, String endDate, String rz) {
		String sql = "SELECT * FROM ThForm WHERE OrgCode = ? AND cast(ThDate as char(10)) >= CONVERT(VARCHAR(10),CONVERT(DATETIME,?),120) and cast(ThDate as char(10)) <= CONVERT(VARCHAR(10),CONVERT(DATETIME,?),120)";
		if (rz.equals("已入账")) {
			sql = sql + " AND rzDate <> ''";
		} else if (rz.equals("未入账")) {
			sql = sql + " AND rzDate = ''";
		}
		Object[] args = new Object[] { orgCode, startDate, endDate };
		List<?> list = super.query(sql, args);
		return (List<ThForm>) list;
	}

	public ThForm getFormByBillNo(String billNo) {
		String sql = "SELECT * FROM thForm WHERE thBillNo = ?";
		Object[] args = new Object[] { billNo };
		List<?> list = super.query(sql, args);
		if (list != null && (!list.isEmpty())) {
			return (ThForm) list.get(0);
		}
		return null;
	}

	public String deleteFanchang(String billNo) {
		String result = "";
		List<String> sqls = new ArrayList<String>();

		String sql = "DELETE FROM ThForm WHERE ThBillNo = '" + billNo + "'";
		sqls.add(sql);
		sql = "DELETE FROM ThDetail WHERE ThBillNo = '" + billNo + "'";
		sqls.add(sql);
		try {
			executeBatch(sqls);
		} catch (DatabaseException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return e.getMessage();
		}
		return result;
	}

	public void rz(String bill) throws DatabaseException {
		CallDTO dto = new CallDTO();
		String sql = "UPDATE thForm SET rzDate WHERE thBillNo = '" + bill + "'";
		String call = "{CALL thrz(?,?)}";
		dto.setBill(bill);
		dto.setCall(call);
		dto.setSql(sql);
		dto.setHxdbName(ConnectionPool.hxDbName);
		super.callProcedure(dto);
	}
}